package com.sky.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    private static final String JSCODE_URL = "https://api.weixin.qq.com/sns/jscode2session";//ctrl+shift+u 大小写切换

    @Autowired
    UserMapper userMapper;

    @Override
    public User login(UserLoginDTO userLoginDTO) {
//        1.调用微信官方接口，获取微信返回的openID
        Map<String ,String> paramMap = new HashMap<>();
        paramMap.put("appid","wx5a2c4e413cfe6c28");//ctrl+d
        paramMap.put("secret","fff99edc0ac0ac2454e13cad3b2e9da2");//ctrl+d
        paramMap.put("js_code", userLoginDTO.getCode());//ctrl+d
        paramMap.put("grant_type","authorization_code");//ctrl+d

        String result = HttpClientUtil.doGet(JSCODE_URL,paramMap);
//        解析微型返回的结果
        JSONObject jsonObject = JSONObject.parseObject(result);
        String openid = jsonObject.getString("openid");
//        2.判断openID是否为null，如果为null，则抛异常提示信息
        if(StringUtils.isEmpty(openid)){
            throw  new LoginFailedException("微信登录失败！");
        }
//        3.先查询数据库中，openID对应的用户是否存在
        User user = userMapper.getByopenId(openid);

//        4.不存在则新增用户
        if(user == null){
            user = new User();
            user.setName("微信用户");
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);

        }

        return user;
    }
}
